04. Quiz: Read Text Files
Reading in plain text files is a common task that you'll see yourself performing over and over. Try implementing the two functions in this quiz:
read_file(filename)
: Read a plain text file and return the contents as a string.read_files(pathname)
: Read all files in a directory and return a dict with contents.
Hit Test Run to run your code, look at the output and check for errors. Then click Submit to have your code evaluated against some tests. Feel free to test run and submit as many times as you want!
You can even modify the code in test_run()
if you need to (e.g. to add a print statement for debugging) - it is only called on Test Run, not on Submit.
Start Quiz:
"""Reading in text files."""
def read_file(filename):
"""Read a plain text file and return the contents as a string."""
pass # TODO: Open "filename", read text and return it
def read_files(path):
"""Read all files that match given path and return a dict with their contents."""
# TODO: Get a list of all files that match path (hint: use glob)
# TODO: Read each file using read_file()
# TODO: Store & return a dict of the form { <filename>: <contents> }
# Note: <filename> is just the filename (e.g. "hieroglyph.txt") not the full path ("data/hieroglyph.txt")
pass
def test_run():
# Test read_file()
print(read_file("data/hieroglyph.txt"))
# Test read_files()
texts = read_files("data/*.txt")
for name in texts:
print("\n***", name, "***")
print(texts[name])
if __name__ == '__main__':
test_run()
User's Answer:
(Note: The answer done by the user is not guaranteed to be correct)
"""Reading in text files."""
import os
import glob
def read_file(filename):
"""Read a plain text file and return the contents as a string."""
with open(filename,"r") as f:
text = f.read()
return text
def read_files(path):
"""Read all files that match given path and return a dict with their contents."""
dic = {}
# TODO: Get a list of all files that match path (hint: use glob)
for filename in glob.glob(path):
with open(filename,'r') as f:
text = f.read()
dic[os.path.basename(filename)]=text;
# TODO: Read each file using read_file()
# TODO: Store & return a dict of the form { <filename>: <contents> }
# Note: <filename> is just the filename (e.g. "hieroglyph.txt") not the full path ("data/hieroglyph.txt")
return dic
def test_run():
# Test read_file()
print(read_file("data/hieroglyph.txt"))
# Test read_files()
texts = read_files("data/*.txt")
for name in texts:
print("\n***", name, "***")
print(texts[name])
if __name__ == '__main__':
test_run()